package com.example.demo.controller;

import com.example.demo.model.LogInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.LogService;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserCotroller {

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    //事务管理器
    @Autowired
    private DataSourceTransactionManager transactionManager;
    // 事务属性对象
    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/add3")
    @Transactional(propagation = Propagation.REQUIRED)
    public int add3(UserInfo userInfo){
       // 非空校验
        if(userInfo==null || !StringUtils.hasLength(userInfo.getUsername())){
        // 非法参数
            return -1;
        }
        int result=0;
        // 添加用户
        int resultByUser=userService.add(userInfo);
        log.info("添加用户的结果："+resultByUser);
        // 添加日志
        LogInfo logInfo=new LogInfo();
        logInfo.setName("添加用户");
        logInfo.setDesc("用户信息："+userInfo);
        int resultByLog=logService.add(logInfo);
        log.info("添加日志结果："+resultByLog);
        if(resultByUser==1 && resultByLog==1){
            result=1;
        }
        return result;
    }

    @RequestMapping("/add")
    public int add(UserInfo userInfo){
        // 获取事务（开启事务）
        TransactionStatus transactionStatus=
        transactionManager.getTransaction(transactionDefinition);
        int result=userService.add(userInfo);
        log.info("添加结果："+result);
        // 回滚事务
        transactionManager.rollback(transactionStatus);
        return result;
    }

    // 开启声明式事务（进入方法自动开启事务，方法正常执行完自动提交事务）
    // 如果发生了未处理的异常会自动回滚事务
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/add2")
    public int add2(UserInfo userInfo) throws InterruptedException{
        int result=0;
        try {
            result = userService.add(userInfo);
            log.info("添加功能II，执行结果："+result);
            int num=10/0; // 声明式事务只想到此之后，因为报错而
        }catch (Exception e){
            log.info("程序执行出现异常："+e.getMessage());
        }
        return result;
    }
}
